const USER_INFO_KEY = 'userInfo'

export default {
  namespaced: true,
  state: {
    user: {},
    authorized: false,
    loginTime: null,
    initialized: false,

    logoInfo: {
      logoid: '',
      appid: '',
      logotype: '',
      logoUrl: '',
      title: '',
      copyright: '',
      versionNumber: '',
      businessLicense: '',
      recordNumber: '',
      recordConnection: '',
      iconUrl: '',
      domainUrl: '',
      platformTitle: '',
      loginTitle: '',
      createTime: '',
      lastmodifytime: '',
      status: ''
    },
  },
  mutations: {
    setUser(state, data) {
      // console.log('setUser', data)
      state.user = data
    },
    setAuthorized(state, data) {
      state.authorized = data
    },
    setLoginTime(state, data) {
      state.loginTime = data
    },
    setInitialized(state, data) {
      state.initialized = data
    },

    setLogoInfo(state, data) {
      state.logoInfo = data
    },
  },
  actions: {
    init({ dispatch, commit, state }) {
      // console.log('initdatadatadata', data)
      // const localData = localStorage.getItem(USER_INFO_KEY)
      let _user = localStorage.getItem(`${window.$app.appId}_user`)
      if (_user && !window.$app?.user?.token) {
        window.$app.user = JSON.parse(_user)
      }
      // console.log('init', _user)
      
      if (_user) {
        try {
          // const { userInfo, loginTime } = JSON.parse(_user)
          const userInfo = JSON.parse(_user)
          // if (Date.now() - loginTime > 7 * 3600000) {
          //   localStorage.removeItem(USER_INFO_KEY)
          // } else {
          dispatch('login', userInfo)
          // }
        } catch (error) {
          console.log(error)
        }
        
        commit('setInitialized', true)
      } else if (!state.initialized) {
        commit('setInitialized', true)
        window.$app.delAuth(true)
      } else {
        commit('setInitialized', true)
      }
    },
    login({ commit }, data) {
      const loginTime = Date.now()
      commit('setUser', data)
      commit('setAuthorized', true)
      commit('setLoginTime', loginTime)
      // localStorage.setItem(
      //   USER_INFO_KEY,
      //   JSON.stringify({
      //     userInfo: data,
      //     loginTime: loginTime
      //   })
      // )
    },
    logout({ commit }) {
      commit('setUser', null)
      commit('setAuthorized', false)
      localStorage.removeItem(USER_INFO_KEY)
    }
  }
}
